package com.hertz.appr.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import com.hertz.appr.dao.IBaseDao;
import com.hertz.appr.pojo.db.Action;
import com.hertz.appr.pojo.db.Member;

public class MemberService {
	
	private Logger log = Logger.getLogger(ActionService.class);
	
	private IBaseDao<Member,Integer> memberDao;
	private Map<String, Member> map;
	
	public void init(){
		log.info("init member cache");
		List<Member> list = memberDao.find("from Member as m where m.flag=?", Member.MEMBER_PERMIT);
		map = new HashMap<String, Member>();
		for(Member member : list){
			map.put(member.getUid() + "-" + member.getProvider(), member);
			log.info(member);
			log.info("put cache");
		}
	}
	public Member getMember(String uid,String provider){
		String hql = "from Member m where m.uid=? and m.provider=?";
		List<Member> list = memberDao.find(hql, uid,provider);
		if(list == null || list.size() == 0){
			log.error("getMember uid=" + uid + ";provider=" + provider);
			log.error("memberList == null || memberList.size==0");
			return null;
		}else{
			return list.get(0);
		}
		
	}
	
	public boolean hasPrivilege(String uid,String provider){
		if(map == null){
			log.info("member cache is null ,init()");
			init();
		}
		log.info("load member from cache");
		Member member = map.get(uid + "-" + provider);
		if(member == null){
			log.info("not in cache ,load from db");
			member = getMember(uid, provider);
			if(member == null ){
				log.info("no member");
				return false;
			}
		}
		map.put(uid + "-" + provider, member);
		if(member.getFlag().equals(Member.MEMBER_PERMIT))
			return true;
		else
			return false;
	}
	
	public void save(Member member){
		if(map == null){
			log.info("member cache is null ,init()");
			init();
		}
		map.put(member.getUid() + "-" + member.getProvider(), member);
		log.info(member);
		log.info("put cache");
		memberDao.save(member);
		log.info("put db");
	}

	public IBaseDao<Member, Integer> getMemberDao() {
		return memberDao;
	}

	public void setMemberDao(IBaseDao<Member, Integer> memberDao) {
		this.memberDao = memberDao;
	}

}
